package com.joysuch.wwyt.openapi.services.serviceV1.impl;

import cn.hutool.core.util.ObjectUtil;
import com.joysuch.wwyt.bp.entity.ApiToken;
import com.joysuch.wwyt.bp.repository.ApiTokenDao;
import com.joysuch.wwyt.core.enums.Status;
import com.joysuch.wwyt.openapi.constants.ApiCode;
import com.joysuch.wwyt.openapi.constants.ApiStatus;
import com.joysuch.wwyt.openapi.controllers.controllerV1.req.ApiV1TokenReq;
import com.joysuch.wwyt.openapi.enums.ApiStaticParameter;
import com.joysuch.wwyt.openapi.exception.ApiV1ExceptionCodeMsg;
import com.joysuch.wwyt.openapi.services.serviceV1.ApiV1TokenService;
import com.joysuch.wwyt.util.Md5Util;
import com.joysuch.wwyt.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author: JamesZY
 * @date: 2021/9/7
 * @description:
 */
@Slf4j
@Service
public class ApiV1TokenServiceImpl implements ApiV1TokenService {
    @Autowired
    private ApiTokenDao dao;
    @Autowired
    private RedissonClient redissonClient;


    @Override
    public String getToken(ApiV1TokenReq req, HttpServletRequest request) throws ApiV1ExceptionCodeMsg {
        String token = this.getHeader(request);
        if (StringUtil.isEmpty(token)) {
            log.error("authentication data is not null");
            throw new ApiV1ExceptionCodeMsg(Status.API_V1_AUTHORIZATION_DATA_IS_NULL_ERROR);
        }
        Boolean trueOrFalse = this.getAuthorization(token, req);
        if (!trueOrFalse) {
            throw new ApiV1ExceptionCodeMsg(Status.API_V1_AUTHORIZATION_DATA_ERROR);
        }
        return generateToken(req);
    }

    private String generateToken(ApiV1TokenReq req) {
        String token = UUID.randomUUID().toString().replace("-", "").toUpperCase();
        ApiToken apiToken = dao.findByAppId(req.getAppId());
        //token生效时间默认为2小时
        redissonClient.getBucket(ApiStaticParameter.API_V1_TOKEN + ":" + token).set(apiToken.getTenentId() + "@" + apiToken.getOrgCode() + "@" + token, ObjectUtil.isEmpty(apiToken.getExpiredTime()) ? 120 : apiToken.getExpiredTime(), TimeUnit.MINUTES);
        return token;
    }

    private Boolean getAuthorization(String token, ApiV1TokenReq req) {
        ApiToken apiToken = dao.findByAppId(req.getAppId());
        if (apiToken == null) {
            return false;
        }
        String md5Str = Md5Util.md5(Md5Util.md5(apiToken.getAppId() + apiToken.getSecret())).toUpperCase();
        if (md5Str.equals(token)) {
            return true;
        } else {
            return false;
        }
    }

    private String getHeader(HttpServletRequest request) {
        return request.getHeader("Authorization");
    }
}
